﻿using TCommon;
using TCommunication.Interface;

namespace TCommunication.Impl;
/// <summary>
/// 
/// </summary>
public class CanCommunication:ICanCommunication
{
    /// <summary>
    /// Can盒名
    /// </summary>
    public string CanBoxName { get; set; } = string.Empty;
    /// <summary>
    /// Can通道号
    /// </summary>
    public int CanBoxChannel { get; set; } = 0;
    /// <summary>
    /// Can通道对象
    /// </summary>
    public ICanChannel? CanChannel { get; set; }
    /// <summary>
    /// 是否连接
    /// </summary>
    public bool IsConnected => CanChannel?.IsOpen ?? false;
    /// <summary>
    /// 连接
    /// </summary>
    /// <returns></returns>
    public OperateResult Connect()
    {
        if (IsConnected)
        {
            return OperateResult.CreateSuccessResult();
        }
        else
        {
            var getCanBoxResult = CanBoxManager.Default.GetCommunication(CanBoxName);
            if (getCanBoxResult.IsSuccess)
            {
                var canBox = getCanBoxResult.Content!;
                if (!canBox.IsConnected)
                {
                    canBox.Connect();
                }
                var createChannelResult = canBox.CreateChannel(CanBoxChannel);
                if (createChannelResult.IsSuccess)
                {
                    CanChannel = createChannelResult.Content!;
                    if (!CanChannel.IsOpen)
                    {
                        return CanChannel.Open();
                    }
                    else
                    {
                        return OperateResult.CreateSuccessResult();
                    }
                }
                else
                {
                    return OperateResult.CreateFailedResult(createChannelResult.Message);
                }
            }
            else
            {
                return OperateResult.CreateFailedResult(getCanBoxResult.Message);
            }
        }
    }
    /// <summary>
    /// 断开连接
    /// </summary>
    /// <returns></returns>
    public OperateResult DisConnect()
    {
        return this.CanChannel?.Close() ?? OperateResult.CreateSuccessResult();
    }
    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
        CanChannel?.Dispose();
    }
}